<script setup lang="ts">
defineOptions({
  name: "GasConsumeRank"
});
import { ref, watch, getCurrentInstance, onMounted, nextTick, reactive, toRefs, computed, onUnmounted } from "vue";
import yearPicker from "@/views/common/energy/components/yearPickerSmall.vue";
import modelTitle from "@/views/common/components/modelTitle/index.vue";
import type { UtilsEChartsOption } from "@pureadmin/utils";
import { PxMessage } from "px-ui";
import { getConsumeCostOverView } from "@/api/energy/consumeCost";
import tableEcharts from "./tableEcharts/index.vue";
import { queryScadaIndicator } from "@/api/machineApi";

interface Props {
  /**  有 title 时传入 */
  title?: string;
  /**  有按钮时传入，传入后会有 btn-click 事件 */
  button?: string;
  /**  模块最低宽度，默认 330px */
  width?: number;
  /**  模块最低高度，默认 200px */
  height?: number;
  /**  是否需要背景阴影，默认为true */
  boxShadow?: boolean;
  /**  是否需要圆角，默认为true */
  borderRidus?: boolean;
  /**  是否暗色，默认为false */
  dark?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  title: "能耗排行-大宗气",
  dark: false,
  width: 330,
  height: 200,
  boxShadow: false,
  borderRidus: false
});

interface queryForm {
  queryTimeGranularity?: string;
  level?: string;
  startTime?: string;
  endTime?: string;
}

type itemStyleType = {
  [key: string]: string;
};

interface dataType {
  name: string;
  value: number;
  itemStyle?: itemStyleType;
}

interface Emits {
  /**  title 右侧按钮点击后触发 */
  (event: "btn-click"): void;
}

const emits = defineEmits<Emits>();

const title_height = computed(() => (props.title ? "38px" : "0px"));
const min_width = computed(() => `${props.width}px`);
const min_height = computed(() => `${props.height}px`);

const energyType = ref("all");

const tablePieKey = ref(Date.now());

const radioOptions = ref<any>([
  {
    label: "all",
    name: "总能耗折标煤",
    size: "small"
  },
  {
    label: "electricity",
    name: "电",
    size: "small"
  },
  {
    label: "water",
    name: "水",
    size: "small"
  },
  {
    label: "ng",
    name: "天然气",
    size: "small"
  },
  {
    label: "steam",
    name: "蒸汽",
    size: "small"
  },
  {
    label: "hot",
    name: "热水",
    size: "small"
  },
  {
    label: "gas",
    name: "大宗气",
    size: "small"
  }
]);

const columnName = ref([
  {
    label: "工艺机台",
    name: ""
  },
  {
    label: "大宗气系统",
    name: ""
  },
  {
    label: "特气系统",
    name: ""
  },
  {
    label: "化学品系统",
    name: ""
  },
  {
    label: "纯水系统",
    name: "STIC_FAB_UPW_FIQ_9020_TOT_ACC_CALCULATE"
  },
  {
    label: "纯水系统",
    name: "STIC_FAB_UPW_FIQ_9022_TOT_ACC_CALCULATE"
  },
  {
    label: "VOC系统",
    name: ""
  },
  {
    label: "废水系统",
    name: "STIC_WWT_CDA_CONSUMPTION"
  },
  {
    label: "制程排气系统",
    name: ""
  },
  {
    label: "Clean room",
    name: ""
  },
  {
    label: "冷热水系统",
    name: ""
  },
  {
    label: "PCW/PV/HV系统",
    name: ""
  }
]);

const tableColumns = ref([
  {
    label: "系统",
    prop: "name",
    align: "left"
  },
  {
    label: "CDA(Nm³)",
    prop: "value1",
    align: "left",
    sortable: true,
    sortOrders: ["ascending", "descending", null],
    sortBy: ["value1"]
  },
  {
    label: "N₂(Nm³)",
    prop: "value2",
    align: "left",
    sortable: true,
    sortOrders: ["ascending", "descending", null],
    sortBy: ["value2"]
  },
  {
    label: "H₂(Nm³)",
    prop: "value3",
    align: "left",
    sortable: true,
    sortOrders: ["ascending", "descending", null],
    sortBy: ["value3"]
  },
  {
    label: "O₂(Nm³)",
    prop: "value4",
    align: "left",
    sortable: true,
    sortOrders: ["ascending", "descending", null],
    sortBy: ["value4"]
  },
  {
    label: "Ar(Nm³)",
    prop: "value5",
    align: "left",
    sortable: true,
    sortOrders: ["ascending", "descending", null],
    sortBy: ["value5"]
  },
  {
    label: "He(Nm³)",
    prop: "value6",
    align: "left",
    sortable: true,
    sortOrders: ["ascending", "descending", null],
    sortBy: ["value6"]
  },
  {
    label: "CO₂(Nm³)",
    prop: "value7",
    align: "left",
    sortable: true,
    sortOrders: ["ascending", "descending", null],
    sortBy: ["value7"]
  }
]);

const { proxy }: any = getCurrentInstance();

// 定义数据
const dateRange = ref<any>([]);

const yearStart = ref("");
const yearEnd = ref("");
// 可选择区间，initYear传参，不传则所有年份有效，小于0判断一下？
const dateValue = ref<any>({ startYear: new Date().getFullYear(), endYear: new Date().getFullYear() });
// const dateValue = ref<any>({});
// 选完/输入完成的回调
const updateStatisticYear: any = (startYear: number, endYear: number) => {
  console.log("选中年份", startYear, endYear);
  dateRange.value = [startYear ? startYear.toString() : "", endYear ? endYear.toString() : ""];
  yearStart.value = `${startYear}-01-01 00:00:00`;
  yearEnd.value = `${endYear}-12-31 23:59:59`;
};

const pageData = ref<any>({});

const costOptions = ref<UtilsEChartsOption>({});

const trendOptions = ref<UtilsEChartsOption>({});

const dataList = ref<any>([]);

const clickHandler = () => emits("btn-click");

// 合并同类项数组
const mergeDataByProperty = (arr, type) => {
  const merged = [];
  let propertyValues = {};
  const keyArr: any = Array.from(new Set(arr.map(item => item.point))) || [];
  for (const val in keyArr) {
    propertyValues[keyArr[val]] = [];
    console.log(val);
    arr.forEach(item => {
      if (item.point === keyArr[val]) {
        propertyValues[keyArr[val]].push({
          name: item[type],
          value: Number(item.sum_value)
        });
      }
    });
  }
  return propertyValues;
};

const getSum = (arr: any) => {
  let sum = 0;
  if (arr && arr.length) {
    for (let i = 0; i < arr.length; i++) {
      sum += arr[i].value ? arr[i].value : 0;
    }
  }
  return Number(Number(sum).toFixed(2)) || 0;
};

const getLabel = str => {
  return columnName.value.find(e => e.name === str).label;
};

const getPageData = async () => {
  // CDA
  const list1 = ["STIC_FAB_UPW_FIQ_9020_TOT_ACC_CALCULATE", "STIC_WWT_CDA_CONSUMPTION"];
  // N2
  const list2 = ["STIC_FAB_UPW_FIQ_9022_TOT_ACC_CALCULATE"];
  // H2
  const list3 = [];
  // O2
  const list4 = [];
  // Ar
  const list5 = [];
  // He
  const list6 = [];
  // CO2
  const list7 = [];
  let type = "";
  switch (queryParams.value.queryTimeGranularity) {
    case "Daily":
      type = "day";
      break;
    case "Monthly":
      type = "month";
      break;
    case "Yearly":
      type = "year";
      break;

    default:
      break;
  }
  const res: any = await queryScadaIndicator({
    contentType: "LIST",
    bucketWidth: 1,
    bucketUnit: type,
    point: [...list1.concat(list2, list3, list4, list5, list6, list7)],
    indicators: ["SUM"],
    startTime: queryParams.value.startTime,
    endTime: queryParams.value.endTime
  });
  const mergeData: any = mergeDataByProperty(res.rows, type) || {};
  console.log(mergeData, "");
  const arr = Object.keys(mergeData) || [];
  const tableData = arr.map(el => {
    return {
      name: getLabel(el),
      // label: el,
      value1: list1.includes(el) ? getSum(mergeData[el]) : "-",
      value2: list2.includes(el) ? getSum(mergeData[el]) : "-",
      value3: list3.includes(el) ? getSum(mergeData[el]) : "-",
      value4: list4.includes(el) ? getSum(mergeData[el]) : "-",
      value5: list5.includes(el) ? getSum(mergeData[el]) : "-",
      value6: list6.includes(el) ? getSum(mergeData[el]) : "-",
      value7: list7.includes(el) ? getSum(mergeData[el]) : "-"
    };
  });
  const chartData = arr.map(el => {
    return {
      name: getLabel(el),
      label: el,
      value: getSum(mergeData[el])
    };
  });
  // dataList.value = tableData;
  const newList = Object.values(
    tableData.reduce((acc, current) => {
      const name = current.name;
      if (!acc[name]) {
        acc[name] = { ...current };
      } else {
        acc[name] = {
          ...acc[name],
          ...Object.fromEntries(Object.entries(current).filter(([key, value]) => key !== "name" && value !== "-"))
        };
      }
      return acc;
    }, {})
  );
  dataList.value = newList;
  costOptions.value = labelLayoutFn(chartData);
  tablePieKey.value = Date.now();
};

const labelLayoutFn = (data: any) => {
  const options: UtilsEChartsOption = {
    color: ["#5B8FF9", "#5AD8A6 ", "#FFB910"],
    tooltip: {
      trigger: "item",
      formatter: `{a} <br/>{b}: {c} ({d}%)`
    },
    grid: {
      top: "15%",
      bottom: "0%"
    },
    // legend: {
    //   type: "scroll", // 设置图例分页类型为滚动
    //   icon: "rect",
    //   orient: "horizontal", // 水平排列
    //   data: (data && data.map(el => el.name)) || []
    // },
    series: [
      {
        name: "能耗排行-大宗气",
        type: "pie",
        labelLine: {
          length: 15
        },
        label: {
          formatter: `{name|{b}}\n{c|{c}}({d|{d}%})`,
          rich: {
            name: {
              fontSize: 10
            },
            c: {
              fontSize: 10
            },
            d: {
              fontSize: 10,
              fontWeight: "bold"
            }
          }
        },
        radius: "50%",
        data: data || []
      }
    ]
  };
  return options;
};

const queryParams = ref<queryForm>({
  queryTimeGranularity: "Monthly",
  level: ""
});

const queryTypeParams = ref({
  energyType: "Electricity"
});

// 获取当月第一天
const getCurrentMonthF = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  let d = "01";
  m = m < 10 ? "0" + m : m;
  return [y, m, d].join("-");
};

// 获取当月最后一天
const getCurrentMonthL = () => {
  let date = new Date();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  let d: any = new Date(y, m, 0).getDate();
  m = m < 10 ? "0" + m : m;
  d = d < 10 ? "0" + d : d;
  return [y, m, d].join("-");
};

const handleChangeFn = (val: string) => {
  //获取新的时间
  let date = new Date();
  //获取当前时间的年份转为字符串
  let year = date.getFullYear().toString();
  //获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
  let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  //获取天，判断是否小于10，如果是在字符串前面拼接'0'
  let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  switch (val) {
    case "Daily":
      dateRange.value = [getCurrentMonthF(), getCurrentMonthL()];
      // queryParams.value.startTime = getCurrentMonthF() + " 00:00:00";
      // queryParams.value.endTime = getCurrentMonthL() + " 23:59:59";
      break;
    case "Monthly":
      dateRange.value = [`${year}-${month}`, `${year}-${month}`];
      // queryParams.value.startTime = dateRange.value[0] + "-01 00:00:00";
      // queryParams.value.endTime = dateRange.value[1] + "-31 23:59:59";
      break;
    case "Yearly":
      let yearS = new Date().getFullYear();
      let yearE = new Date().getFullYear();
      yearStart.value = `${yearS}-01-01 00:00:00`;
      yearEnd.value = `${yearE}-12-31 23:59:59`;
      break;
    default:
      break;
  }
};

// 校验时间范围不为空
const checkDate = () => {
  if (queryParams.value.queryTimeGranularity) {
    if (dateRange.value && dateRange.value.length) {
      return true;
    }
    if (queryParams.value.startTime && queryParams.value.endTime) {
      return true;
    }
  }
};

// 获取某月最后一天
const getMonthLastDay = (y, m) => {
  let date = new Date(y, m - 1, "01");
  date.setDate(1);
  date.setMonth(date.getMonth() + 1);
  let cdate = new Date(date.getTime() - 1000 * 60 * 60 * 24);
  return cdate.getDate();
};

const factoryName = ref("");
/** 搜索按钮操作 */
function handleQuery() {
  factoryName.value = queryParams.value.level;
  if (queryParams.value.queryTimeGranularity === "Daily") {
    queryParams.value.startTime = dateRange.value[0] + " 00:00:00";
    queryParams.value.endTime = dateRange.value[1] + " 23:59:59";
    // queryParams.value.startTime =
    //   queryParams.value.startTime.indexOf("00") != -1 ? queryParams.value.startTime : queryParams.value.startTime + " 00:00:00";
    // queryParams.value.endTime = queryParams.value.endTime.indexOf("59") != -1 ? queryParams.value.endTime : queryParams.value.endTime + " 23:59:59";
  } else if (queryParams.value.queryTimeGranularity === "Monthly") {
    queryParams.value.startTime = dateRange.value[0].indexOf("00") != -1 ? dateRange.value[0] : dateRange.value[0] + "-01 00:00:00";
    const d = getMonthLastDay(Number(dateRange.value[1].split("-")[0]), Number(dateRange.value[1].split("-")[1]));
    queryParams.value.endTime = dateRange.value[1].indexOf("59") != -1 ? dateRange.value[1] : dateRange.value[1] + "-" + d + " 23:59:59";
  } else {
    queryParams.value.startTime = yearStart.value;
    queryParams.value.endTime = yearEnd.value;
  }
  console.log(queryParams.value.startTime, queryParams.value.endTime);
  proxy.$refs["queryRef"].validate(valid => {
    if (!valid) return;
    if (queryParams.value.queryTimeGranularity) {
      if (!checkDate()) {
        return PxMessage({
          type: "warning",
          message: "时间范围不能为空"
        });
      }
    }
  });
  getPageData();
}
/** 重置按钮操作 */
function resetQuery() {
  initQuery();
}

// 反转数组
const reverseArray = (arr: any[]) => {
  let newArr = [];
  arr.forEach((item: any) => {
    newArr.unshift(item);
  });
  return newArr;
};

const initQuery = () => {
  queryParams.value.queryTimeGranularity = "Monthly";
  //获取新的时间
  let date = new Date();
  //获取当前时间的年份转为字符串
  let year = date.getFullYear().toString();
  //获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
  let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString();
  //获取天，判断是否小于10，如果是在字符串前面拼接'0'
  let da = date.getDate() < 10 ? "0" + date.getDate().toString() : date.getDate().toString();
  let y = date.getFullYear(); // 获取年
  let m: any = date.getMonth() + 1; // 获取月
  dateRange.value = [`${year}-${month}`, `${year}-${month}`];
  queryParams.value.startTime = getCurrentMonthF() + " 00:00:00";
  queryParams.value.endTime = getCurrentMonthL() + " 23:59:59";
  queryParams.value.level = "";
  getPageData();
};

onMounted(async () => {
  initQuery();
});
</script>

<template>
  <div class="today-task" :class="{ boxShadow, borderRidus, 'model-title-com-dark': dark }">
    <modelTitle v-if="title" :title="title">
      <div class="model-title-slot">
        <px-button v-if="button" type="primary" size="small" plain @click="clickHandler">{{ button }}</px-button>
        <px-form ref="queryRef" class="custom-form-ui inspection-form" :model="queryParams" :inline="true" label-width="100px">
          <px-form-item label="时间维度" prop="dataFormat" style="width: 280px">
            <px-radio-group v-model="queryParams.queryTimeGranularity" style="margin-left: 10px" @change="handleChangeFn">
              <!-- <px-radio size="small" label="Hourly">小时</px-radio> -->
              <px-radio size="small" label="Daily">日</px-radio>
              <px-radio size="small" label="Monthly">月</px-radio>
              <px-radio size="small" label="Yearly">年</px-radio>
            </px-radio-group>
          </px-form-item>
          <px-form-item label="时间范围" style="width: 380px">
            <!-- <px-time-picker
              v-if="queryParams.queryTimeGranularity === 'Hourly'"
              v-model="dateRange"
              is-range
              range-separator="-"
              format="HH"
              value-format="HH"
              start-placeholder="开始小时"
              end-placeholder="结束小时"
            /> -->
            <px-date-picker
              v-if="queryParams.queryTimeGranularity === 'Daily'"
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
            <px-date-picker
              v-if="queryParams.queryTimeGranularity === 'Monthly'"
              v-model="dateRange"
              type="monthrange"
              value-format="YYYY-MM"
              range-separator="-"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
            />
            <!-- <div v-else-if="queryParams.queryTimeGranularity === 'Yearly'" class="select_year">
              <px-date-picker v-model="queryParams.startTime" value-format="YYYY" type="year" placeholder="开始年份" />
              <span>&nbsp;-&nbsp;</span>
              <px-date-picker v-model="queryParams.endTime" value-format="YYYY" type="year" placeholder="结束年份" />
            </div> -->
            <div v-if="queryParams.queryTimeGranularity === 'Yearly'">
              <yearPicker ref="statisticPicker" :labelWidth="0" labelText="" :initYear="dateValue" @updateTimeRange="updateStatisticYear" />
            </div>
          </px-form-item>
          <!-- <px-form-item label="厂区">
            <px-select v-model="queryParams.level" clearable placeholder="请选择层级">
              <px-option v-for="item in systemList" :key="item.value" :label="item.name" :value="item.value" />
            </px-select>
          </px-form-item> -->
          <px-button type="primary" icon="" @click="handleQuery">搜索</px-button>
          <px-button icon="" @click="resetQuery">重置</px-button>
        </px-form>
      </div>
    </modelTitle>
    <div class="today-task-com">
      <tableEcharts
        :key="tablePieKey"
        :tableColumns="tableColumns"
        :dataList="dataList"
        :options="costOptions"
        :energyType="energyType"
        :borderRidus="false"
        :boxShadow="false"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.today-task {
  width: 100%;
  height: 100%;
  padding: 16px;
  background-color: #fff;

  .model-title-slot {
    display: flex;
    gap: 16px;
    align-items: center;

    .right-text {
      font-weight: 600;
      line-height: 1;
      color: var(--px-color-primary);
    }

    .px-icon {
      cursor: pointer;
    }
  }

  .today-task-com {
    width: 100%;
    height: calc(100% - v-bind(title_height));
  }
}

.px-form-item {
  margin-bottom: 0;
}

.boxShadow {
  box-shadow: 0 0 10px rgb(0 37 86 / 12%);
}

.borderRidus {
  border-radius: 4px;
}

.model-title-com-dark {
  color: #fff;
  background: linear-gradient(90deg, #062e51ff, #001e3bff);
  border: 1px solid #83b2ffff;
  box-shadow: inset 0 0 10px 0 #83b2ffff;

  .title-text {
    color: #fff !important;
  }
}
</style>
